<?php
/**
 * Description: 整体妆容数据处理类
 * Author: hezhizheng
 * Date: 2018/9/7
 * Time: 19:38
 * Created by Created by Panxsoft.
 */

namespace App\Services\Repositories\Pack;

use App\Http\Requests\Admin\Customer\Store\PackPatchRequest;
use App\Models\Customer\Asset;
use App\Models\Store\Pack;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class PackService
{
    /**
     * @param Collection $packs
     */
    public function transformPackAssetsProducts(Collection $packs): void
    {
        $packs->each(function (Pack $pack) {
            $pack->assets->each(function (Asset $asset) use ($pack) {
                // 整体妆容已修改成多素材关联多商品，前端之前取的是 products 字段, 用 assetPivotProducts 替换掉
                $asset->products = $this->assembleProducts($asset->assetPivotProducts, $pack->id);
//                $asset->products = $asset->getPivotProductsForPackIds([$pack->id]);
                $asset->addHidden(['assetPivotProducts']);
            });
        });
    }

    /**
     * @param Collection $products
     * @param $pack_id
     * @return Collection
     */
    private function assembleProducts(Collection $products, $pack_id)
    {
        if (!$products->count()) return $products;

        $data = $products->filter(function ($product) use ($pack_id) {
            return $product->pivot->pack_id === $pack_id;
        });

        return $data->values();
    }

    /**
     * @param Request|PackPatchRequest $request
     * @return array
     */
    public function assemblePack(Request $request)
    {
        $data = [
            'is_deleted'       => $request->is_deleted,
            'priority'         => $request->priority,
            'name'             => $request->name,
        ];

        if ( $request->pack_category_id ) {
            $data['pack_category_id'] = $request->pack_category_id;
        }

        if (is_file($request->thumb)){
            $data['thumb'] = $request->thumb;
        }

        return $data;
    }
}